package com.tarena.luban.demo.gateway.handle;

import com.tarena.luban.demo.gateway.ex.GatewayException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class MyErrorHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {

        String message = null;
        if(ex instanceof GatewayException){
            // 认证失败异常
            GatewayException e = (GatewayException)ex;
            message = e.getMessage();
        }else{
            // 其它异常
            message = "系统异常";
        }

        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
        return response.writeWith(Mono.fromSupplier(
                ()->response.bufferFactory().wrap(bytes)));
    }
}








